<?php

/**
 * UserIdentity.php
 */
class UserIdentity extends CUserIdentity {

    /**
     * @var integer id of logged user
     */
    private $_id;
    private $_model;

    public function getModel() {
        return $this->_model;
    }

    /**
     * Authenticates username and password
     * @return boolean CUserIdentity::ERROR_NONE if successful authentication
     */
    public function authenticate() {
        if(strpos($this->username, '@')){
            $attribute = 'email';
        }else{
            $attribute = 'username';
        }
        $user = User::model()->find('LOWER('.$attribute.')=?', array(strtolower($this->username)));

        if ($user === null) {
            $this->errorCode = CBaseUserIdentity::ERROR_UNKNOWN_IDENTITY;
        } elseif (!$user->validatePassword($this->password)) {
            $this->errorCode = CBaseUserIdentity::ERROR_PASSWORD_INVALID;
        } else {
            $this->_model = $user;
            $this->_id = $user->user_id;
            $this->username = $user->display_name;
            $this->errorCode = self::ERROR_NONE;
        }

        return !$this->errorCode;
    }

    /**
     * Creates an authenticated user with no passwords for registration
     * process (checkout)
     * @param string $username
     * @return self
     */
    public static function createAuthenticatedIdentity($id, $username) {
        $identity = new self($username, '');
        $identity->_id = $id;
        $identity->errorCode = self::ERROR_NONE;
        return $identity;
    }

    /**
     *
     * @return integer id of the logged user, null if not set
     */
    public function getId() {
        return $this->_id;
    }

}